/* eslint-disable no-undef */
import axios from "axios"
import { Message } from "element-ui"
import { downloadFile, generateReqKey } from "./tools"
import lockr from "lockr"
import router from "@/router"
// import iconv from "iconv-lite"
let requestQueue = new Map()
const service = axios.create({
  baseURL: "",
  timeout: 20000,
  withCredentials: true
})

service.interceptors.request.use(
  (config) => {
    // config.url = config.otherUrl ? config.otherUrl : baseUrl + config.url
    config.headers["Authorization"] = `Bearer ${lockr.get("token")}`
    if (config.idempotent) {
      const key = generateReqKey(config)
      config.cancelToken = new axios.CancelToken((cancel) => {
        if (requestQueue.has(key)) {
          cancel(`Request canceled: ${key}`)
        }
        requestQueue.set(key, cancel)
      })
    }

    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  async (response) => {
    const status = response.status
    if (status > 300 || status < 200) {
      return Promise.reject(
        new Error(
          (response.data && response.data.message) ||
            response.message ||
            "Error"
        )
      )
    }
    const key = generateReqKey(response.config)
    requestQueue.delete(key)
    if (response.data.type === "application/x-msdownload") {
      if (response.headers["content-disposition"]) {
        let fileName = ""
        fileName = response.headers["content-disposition"]
          .split(";")[1]
          .split("filename=")[1]
        fileName = decodeURIComponent(fileName)
        console.log(fileName)
        downloadFile(response.data, fileName)
      }
      return response.data
    }
    if (response.status === 206) {
      return response.data
    }
    const res = response.data
    if (res.code != 0) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || "Error"))
    } else {
      return res
    }
  },
  (error) => {
    const status = error.status
    if (error && axios.isCancel(error)) {
      console.log("重复点击")
      return
    }

    if (status == 401) {
      Message({
        message: "登录过期，请重新登录",
        type: "error",
        duration: 5 * 1000
      })
      lockr.rm("token")
      lockr.rm("userInfo")
      lockr.rm("menuList")
      lockr.rm("routerList")
      router.push("/login")
      return
    }
    const message = error.response.data.message || error.message || "Error"
    Message({
      message: message,
      type: "error",
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
/**
 * @description 请求头Content-Type
 */
export const HeadersContentType = {
  urlencoded: "application/x-www-form-urlencoded;charset=utf-8",
  json: "application/json;charset=utf-8",
  multipart: "multipart/form-data"
}
